<template>
    <div class="article-list-edit">
        <div class="article-list-edit-card">
            <Row :gutter="25">
                <Col span="10">
                    <Form ref="formArticleData" :model="formArticleData" :rules="ruleArticleData" :label-width="80">
                        <!--<FormItem label="是否显示">-->
                        <!--<i-switch v-model="formArticleData.switch" size="large">-->
                        <!--<span slot="open">显示</span>-->
                        <!--<span slot="close">隐藏</span>-->
                        <!--</i-switch>-->
                        <!--</FormItem>-->
                        <FormItem label="商品名称" prop="title">
                            <Input v-model="formArticleData.title" placeholder="请输入商品名称"></Input>
                        </FormItem>
                        <FormItem label="商品原价" prop="type">
                            <Input v-model="formArticleData.price" placeholder="请输入商品价格"></Input>
                        </FormItem>
                        <FormItem label="会员价" prop="vip">
                            <Input v-model="formArticleData.vip" placeholder="请输入会员价"></Input>
                        </FormItem>
                        <!--<FormItem label="关键字" prop="font">-->
                        <!--<Input v-model="formArticleData.font" placeholder="请输入关键字"></Input>-->
                        <!--</FormItem>-->
                        <!--<FormItem label="排序号"  prop="num">-->
                        <!--<Input number v-model="formArticleData.num" placeholder="请输入排序号"></Input>-->
                        <!--</FormItem>-->
                    </Form>
                    <Card>
                        <p slot="title">
                            <a><Icon type="ios-cloud-upload-outline"></Icon> 商品图片上传</a>
                        </p>
                        <Upload accept="image/png, image/jpeg, image/gif, image/jpg" type="drag" action="?" :before-upload="handleBeforeUpload">
                            <div class="upImg">
                                <a><Icon type="ios-cloud-upload" size="52"></Icon></a>
                                <p>点击或者拖拽上传商品图片</p>
                            </div>
                        </Upload>
                    </Card>

                </Col>
                <Col span="12">

                </Col>
                <Col span="14">
                    <Row :gutter="10">
                        <Col span="14">
                            <Card style="height: 362px;margin-bottom: 20px">
                                <p slot="title">
                                    <a><Icon type="ios-person"></Icon> 商品图片展示</a>
                                </p>
                                <a slot="extra" @click="imgSrc = ''"><Icon type="close"></Icon>清除</a>
                                <img class="imgUp" v-if="imgSrc!=''" :src="imgSrc"/>
                            </Card>
                            <Upload accept="image/png, image/jpeg, image/gif, image/jpg" type="drag" action="?" :before-upload="handleBeforeContentUpload">
                                <div class="upImgContent">
                                    <a><Icon type="ios-cloud-upload" size="52"></Icon></a>
                                    <p>点击或者拖拽上传详情图片</p>
                                </div>
                            </Upload>
                        </Col>
                        <!--<Col span="12" class="articleImgChange">-->
                        <!--<img v-if="imgSrc!=''" :src="imgSrc"/>-->
                        <!--</Col>-->
                    </Row>
                </Col>
            </Row>
            <textarea class='tinymce-textarea' id="tinymceEditer"></textarea>
            <div class="subCon">
                <Button type="primary" @click="handleSubmit">提交</Button>
                <Button @click="handleReset">重置</Button>
            </div>
        </div>
    </div>
</template>
<script>
    import tinymce from 'tinymce';
    export default {
        name: "goods-add",
        data() {
            const validateNum = (rule, value, callback) => {
                if (value === "") {
                    return callback(new Error('排序号不能为空'));
                }
                // 模拟异步验证效果
                setTimeout(() => {
                    if (!Number.isInteger(value)) {
                        callback(new Error('请输入数字值'));
                    } else {
                        callback();
                    }
                }, 1000);
            };
            return {
                typeList: [],//
                formArticleData: {
                    title: "",
                    type: "",
                    price: '',
                    vip:'',
                    switch: true,//默认显示

                    // font:"",
                    // num:"",
                },
                ruleArticleData: {
                    title: [
                        {required: true, message: '商品名称不能为空', trigger: 'blur'}
                    ],
                    price: [
                        {required: true, message: '价格不能为空', trigger: 'blur'}
                    ],
                    vip: [
                        {required: true, message: '会员价不能为空', trigger: 'blur'}
                    ],
                    // font: [
                    //     { required: true, message: '请输入关键字', trigger: 'blur' }
                    // ],
                    // num: [
                    //     {required: true, validator: validateNum, trigger: 'blur'}
                    // ]
                },
                content: "",
                imgSrc: "",//
                isBase64: false,
                imgContent: '',
            }
        },
        mounted() {
            if (this.$route.query.isEdit) {
                this.getEditCon()
            } else {
                this.init();
            }
            // this.getArticleType()
        },
        methods: {
            // getArticleType(){
            //     this.getJsonData("Articletype/getArticleType",{})
            //         .then((res)=>{
            //             this.typeList=res.data
            //         })
            // },
            //获取需要修改的信息
            getEditCon() {
                this.getJsonData('ProjectGoods/index', {id: this.$route.query.id})
                    .then((res) => {
                        this.formArticleData.title = res.goods[0].name;
                        this.formArticleData.price = res.goods[0].old_price;
                        this.formArticleData.vip = res.goods[0].price;
                        this.content = res.goods[0].content;
                        this.imgSrc = res.goods[0].image;
                        this.init();
                        tinymce.get('tinymceEditer').setContent(vm.content)
                    });
                // this.getJsonData("Articles/queryone",{articleId:this.$route.query.id})
                //     .then((res)=>{
                //         this.formArticleData.title=res.data.articletitle
                //         // this.formArticleData.switch=res.data.isshow==1?true:false
                //         // this.formArticleData.font=res.data.articlekey
                //         this.content=res.data.articlecontent
                //         this.formArticleData.type=res.data.catid
                //         // this.formArticleData.num=parseFloat(res.data.articlesort)
                //         this.imgSrc=res.data.articleimg
                //         this.init();
                //     })
            },
            //提交
            handleSubmit() {
                this.$refs.formArticleData.validate((valid) => {
                    if (valid) {
                        // if(this.imgSrc==""){
                        //     this.$Message.warning("请选择图片")
                        // }else{
                        if (this.$route.query.isEdit) {
                            if (this.isBase64) {
                                this.$Loading.start();
                                // this.upBaseImg("User/uploadPic",{image:this.imgSrc})
                                //     .then((res) =>{
                                // tinymce.get('tinymceEditer').setContent(`<img src='${res.url}'/>`)
                                // this.imgSrc = res.url
                                // })
                            } else {
                                this.$Loading.start();
                                this.editArticle()
                            }
                        } else {
                            //新增方法
                            this.$Loading.start();
                            this.addArticle(this.imgSrc)
                            // this.upBaseImg("User/uploadPic",{image:this.imgSrc})
                            //     .then((res) =>{
                            //         this.addArticle(res.url)
                            //     })
                        }
                    }
                })
            },
            editArticle(url) {
                this.getJsonData("ProjectGoods/addGood", {
                    id: this.$route.query.id,
                    name: this.formArticleData.title,
                    // isShow:this.formArticleData.switch?1:-1,
                    content: tinymce.get('tinymceEditer').getBody().innerHTML,
                    price: this.formArticleData.vip,
                    old_price: this.formArticleData.price,
                    image: this.imgSrc
                    // type:this.formArticleData.font,
                    // content:this.formArticleData.num,
                    // articleImg:this.isBase64?url:this.imgSrc,
                })
                    .then((res) => {
                        this.$Message.success("修改成功")
                        this.$router.back()
                    })
            },
            addArticle(url) {
                this.getJsonData("ProjectGoods/addGood", {
                    name: this.formArticleData.title,
                    // isShow:this.formArticleData.switch?1:-1,
                    content: tinymce.get('tinymceEditer').getBody().innerHTML,
                    price: this.formArticleData.vip,
                    image:this.imgSrc,
                    old_price: this.formArticleData.price,
                    // articleKey:this.formArticleData.font,
                    // articleSort:this.formArticleData.num,
                    // catId:this.formArticleData.type,
                    // image:url,
                })
                    .then((res) => {
                        this.$Message.success("新增成功")
                        this.$router.back()
                    })
            },
            //重置
            handleReset() {
                this.$refs.formArticleData.resetFields();
            },
            //初始化方法
            init() {
                this.$nextTick(() => {
                    let vm = this;
                    let height = document.body.offsetHeight - 600;
                    tinymce.init({
                        selector: '#tinymceEditer',
                        branding: false,
                        elementpath: false,
                        height: height,
                        language: 'zh_CN.GB2312',
                        menubar: 'edit insert view format table tools',
                        plugins: [
                            'advlist autolink lists link image charmap print preview hr anchor pagebreak imagetools',
                            'searchreplace visualblocks visualchars code fullpage',
                            'insertdatetime media nonbreaking save table contextmenu directionality',
                            'emoticons paste textcolor colorpicker textpattern imagetools codesample'
                        ],
                        toolbar1: ' newnote print preview | undo redo | insert | styleselect | forecolor backcolor bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image emoticons media codesample',
                        autosave_interval: '20s',
                        image_advtab: true,
                        table_default_styles: {
                            width: '100%',
                            borderCollapse: 'collapse'
                        },
                        setup: function (editor) {
                            editor.on('init', function (e) {
                                vm.spinShow = false;
                                tinymce.get('tinymceEditer').setContent(vm.content);//赋值内容
                            });
                            editor.on('keydown', function (e) {
                                /*localStorage.editorContent = tinymce.get('tinymceEditer').getContent();*/
                            });
                        }
                    });
                });
            },
            handleBeforeUpload(file) {
                if ((Math.round(file.size / 1024 * 100) / 100) < 2000) {
                    this.caijianImg(file)
                } else {
                    this.$Notice.error({
                        title: '文件过大',
                        desc: '文件 ' + file.name + '/' + (Math.round(file.size / 1024 * 100) / 100) + 'KB' + '，请上传 2M 以内的图片。',
                        duration: 4.5
                    });
                }
                //禁止默认上传
                return false
            },
            caijianImg(file) {
                let reader = new FileReader();
                reader.onload = () => {
                    this.upImg(reader.result)
                    // this.imgSrc=reader.result
                    this.isBase64 = true
                    reader.onload = null;
                };
                reader.readAsDataURL(file);
            },
            upImg(image) {
                this.upBaseImg("User/uploadPic", {image})
                    .then((res) => {
                        this.imgSrc = res.url
                        // tinymce.get('tinymceEditer').setContent(tinymce.get('tinymceEditer').getBody().innerHTML + `<img src='${res.url}'/>`)
                    })
            },

            handleBeforeContentUpload(file){
                if((Math.round(file.size/1024*100)/100)<2000){
                    this.caijianContentImg(file)
                }else{
                    this.$Notice.error({
                        title: '文件过大',
                        desc: '文件 '+file.name +'/'+(Math.round(file.size/1024*100)/100)+'KB'+'，请上传 2M 以内的图片。',
                        duration:4.5
                    });
                }
                //禁止默认上传
                return false
            },
            caijianContentImg(file){
                let reader = new FileReader();
                reader.onload = () => {
                    this.ContentupImg(reader.result)
                    reader.onload = null;
                };
                reader.readAsDataURL(file);
            },
            ContentupImg(image){
                this.upBaseImg("User/uploadPic",{image})
                    .then((res) =>{
                        this.imgContent=res.url
                        tinymce.get('tinymceEditer').setContent(tinymce.get('tinymceEditer').getBody().innerHTML + `<img src='${res.url}'/>`)
                    })
            },
        },
        //销毁初始化
        destroyed () {
            tinymce.get('tinymceEditer').destroy();
        }
    }

</script>
<style lang="less">
    @import "./goods-add";
</style>